local addonName, addon = ...

addon.MAX_SPACING, addon.MIN_SPACING = 256, 8

local L = setmetatable({ }, { __index = function(self, key)
	self[key] = key
	return key
end })
addon.L = L

--[[----------------------------------------------------------------------------
Defaults
------------------------------------------------------------------------------]]
addon.defaultSettings = {
	absolute = true,
	backdropColor = { 0.85, 0.85, 0.85, 0.55 },
	backdropEnable = true,
	backdropIndependent = false,
	centerColor = { 1, 0, 0, 1 },
	centerThickness = 1,
	gridColor = { 0, 0, 0, 1 },
	gridThickness = 1,
	hide = false,
	independent = false,
	overlay = false,
	spacingX = 32,
	spacingY = 32,
	squaring = true,
	window = 1
}

--[[----------------------------------------------------------------------------
Tooltip support
------------------------------------------------------------------------------]]
local tooltip

local function UpdateTooltip()
	local settings, NORMAL_FONT_COLOR = addon.db.profile, NORMAL_FONT_COLOR
	local red, green, blue = NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b
	tooltip:ClearLines()
	tooltip:SetText(addonName, 1, 1, 1)
	tooltip:AddDoubleLine(L["Left-Click"], L["Toggle Grid"], 0.15, 0.85, 0.15, red, green, blue, true)
	if settings.backdropIndependent or not settings.hide then
		tooltip:AddDoubleLine(L["CTRL-Left-Click"], L["Toggle Backdrop"], 0.15, 0.85, 0.15, red, green, blue, true)
	end
	if not settings.hide then
		tooltip:AddDoubleLine(L["Middle-Click"], L["Background/Foreground"], 0.15, 0.85, 0.15, red, green, blue, true)
		if settings.independent then
			tooltip:AddDoubleLine(L["Mouse Wheel"], L["X-Axis Spacing"], 0.15, 0.85, 0.15, red, green, blue, true)
			tooltip:AddDoubleLine(L["CTRL-Mouse Wheel"], L["Y-Axis Spacing"], 0.15, 0.85, 0.15, red, green, blue, true)
		else
			tooltip:AddDoubleLine(L["Mouse Wheel"], L["Line Spacing"], 0.15, 0.85, 0.15, red, green, blue, true)
		end
	end
	if addon.config then
		tooltip:AddDoubleLine(L["Right-Click"], L["Toggle Configuration"], 0.15, 0.85, 0.15, red, green, blue, true)
	end
	tooltip:Show()
end

--[[----------------------------------------------------------------------------
OnClick handler for LDB plugin and also used with slash command processing
------------------------------------------------------------------------------]]
local function OnClick(plugin, button)
	if button ~= 'RightButton' then
		local settings, field = addon.db.profile
		if plugin == addon then													-- Slash command handler
			field = button
		elseif button == 'LeftButton' then
			if (settings.backdropIndependent or not settings.hide) and IsControlKeyDown() then											-- Normal OnClick behavior
				field = "backdropEnable"
			else
				field = "hide"
			end
		elseif button == 'MiddleButton' then
			if not settings.hide then
				field = "overlay"
			end
		end
		if not field then return end
		settings[field] = not settings[field]
		addon.UpdateState()
		if tooltip and (field == "hide" or field == "backdropEnable") then
			UpdateTooltip()
		end
		if addon.config then
			addon.config:Refresh()
		end
	elseif addon.config then
		if addon.config:IsVisible() then
			InterfaceOptionsFrame:Hide()
		else
			addon.config()
		end
	end
end

--[[----------------------------------------------------------------------------
Config mode support
------------------------------------------------------------------------------]]
if type(CONFIGMODE_CALLBACKS) ~= 'table' then
	CONFIGMODE_CALLBACKS = { }
end

function addon.ConfigMode(action)
	local mode
	if action == 'ON' then
		mode = false
	elseif action == 'OFF' then
		mode = true
	end
	if mode == nil or mode == addon.db.profile.hide then return end
	addon.db.profile.hide = mode
	addon.UpdateState()
	if tooltip then
		UpdateTooltip()
	end
	if addon.config then
		addon.config:Refresh()
	end
end

--[[----------------------------------------------------------------------------
Quicklauncher
------------------------------------------------------------------------------]]
LibStub('LibDataBroker-1.1'):NewDataObject(addonName, {
	type = 'launcher',
	icon = [[Interface\AddOns\]] .. addonName .. [[\Icon]],
	label = addonName,
	OnClick = OnClick,

	OnEnter = function(plugin)
		tooltip = GameTooltip
		tooltip:SetOwner(plugin, 'ANCHOR_NONE')

		if plugin.AttachFrame then
			plugin:AttachFrame(tooltip)
		else
			tooltip:ClearAllPoints()
			local window, _, pluginCenter = plugin, plugin:GetCenter()
			while(window ~= UIParent and window ~= WorldFrame and window ~= nil) do
				window = window:GetParent()
			end
			local _, windowCenter = (window or addon.grid):GetCenter()
			if pluginCenter >= windowCenter then
				tooltip:SetPoint('TOP', plugin, 'BOTTOM', 0, 0)
			else
				tooltip:SetPoint('BOTTOM', plugin, 'TOP', 0, 0)
			end
		end

		UpdateTooltip()
	end,

	OnLeave = function(plugin)
		if tooltip then
			if tooltip:IsOwned(plugin) then
				tooltip:Hide()
			end
			tooltip = nil
		end
	end,

	OnMouseWheel = function(plugin, delta)
		local settings = addon.db.profile
		if settings.hide then return end
		local field = (settings.independent and IsControlKeyDown()) and "spacingY" or "spacingX"
		local spacing = settings[field] + delta
		if spacing < addon.MIN_SPACING then
			spacing = addon.MIN_SPACING
		elseif spacing > addon.MAX_SPACING then
			spacing = addon.MAX_SPACING
		end
		if spacing ~= settings[field] then
			settings[field] = spacing
			addon.DrawGrid()
			if addon.config then
				addon.config:Refresh()
			end
		end
	end
})

--[[----------------------------------------------------------------------------
Slash command
------------------------------------------------------------------------------]]
_G['SLASH_' .. addonName .. 1] = '/' .. addonName
_G['SLASH_' .. addonName .. 2] = "/gpaper"

SlashCmdList[addonName] = function(command)
	command = strsplit(" ", command:gsub("%s+", " "):lower())
	local button
	if command == "backdrop" then
		button = "backdropEnable"
	elseif command == "config" or command == "gui" then
		button = 'RightButton'
	elseif command == "overlay" then
		button = "overlay"
	end
	OnClick(addon, button or "hide")											-- Passing addon has special meaning
end

--[[----------------------------------------------------------------------------
Load on demand configuration
------------------------------------------------------------------------------]]
local LOA = LibStub('LibOptionsAssist-1.1', true)
if not (LOA and select(2, GetAddOnInfo(addonName .. '_Config'))) then return end	-- Make sure config support exists

addon.config = LOA.AddEntry(addonName, nil, function()
	local configName = addonName .. '_Config'
	addon.addonName, _G[configName] = addonName, addon
	LOA.LoadModule(configName)
	addon.addonName, _G[configName] = nil, nil
end)
